package com.whitedust.top30;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author A
 * @since 2025/11/3 19:15
 */

public class Top28 {
    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length == 0) return null;
        Arrays.sort(intervals, (a, b) -> {
            return a[0] - b[0];
        });
        List<int[]> res = new ArrayList<>();
        int left = intervals[0][0];
        int maxRight = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            if (intervals[i][0] <= maxRight && intervals[i][1] <= maxRight) continue;
            if (intervals[i][0] <= maxRight && intervals[i][1] >= maxRight) maxRight = intervals[i][1];
            if (intervals[i][0] > maxRight) {
                res.add(new int[]{left, maxRight});
                left = intervals[i][0];
                maxRight = intervals[i][1];
            }
        }
        res.add(new int[]{left, maxRight});
        return res.toArray(new int[][]{});
    }
}
